package pl.un4giv3n.mightvsmagic.action.clan;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.Clan;
import pl.un4giv3n.mightvsmagic.entity.Guardian;
import pl.un4giv3n.mightvsmagic.entity.User;

public class CreateClanAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	private User user;
	private String clanName;
	private Long guardianId;
	private Guardian guardian;
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		if(!validateData(entityManager)){
			entityManager.close();
			return ERROR;
		}
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		Clan clan = new Clan();
		clan.setGuardian(guardian);
		clan.setName(clanName);
		clan.addUser(user);
		user.setClanAdmin(true);
		user.setClanMod(true);
		entityManager.persist(clan);
		user.setClan(clan);
		entityManager.merge(user);
		entityManager.flush();
		transaction.commit();
		return SUCCESS;
	}
	@SuppressWarnings("unchecked")
	private boolean validateData(EntityManager em) {
		boolean valid = true;
		if(user.getClan() == null){
			if(user.isClanAcceptancePending()){
				addActionError("Nie możesz założyc klanu oczekując na przyjęcie do innego klanu");
				valid = false;
			}
			guardian = em.find(Guardian.class, guardianId);
			if(guardian == null){
				addActionError("Nie wybrano patrona klanu");
				valid = false;
			}
			Query query = em.createNamedQuery("find.clan.by.name");
			query.setParameter("name", clanName);
			List<Clan> clans = query.getResultList();
			if(clans != null && !clans.isEmpty()){
				addActionError("Ta nazwa klanu jest już zajęta");
				valid = false;
			}
		}else{
			addActionError("Nie możesz założyc klanu ponieważ jesteś już członkiem innego klanu");
			valid = false;
		}
		return valid;
	}
	public String getClanName() {
		return clanName;
	}
	public void setClanName(String clanName) {
		this.clanName = clanName;
	}
	public Long getGuardianId() {
		return guardianId;
	}
	public void setGuardianId(Long guardianId) {
		this.guardianId = guardianId;
	}
	
}
